package com.xing.servlet;

import com.xing.domain.User;
import com.xing.service.UserService;
import com.xing.service.impl.UserServiceImpl;
import com.xing.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
 * 静，谦虚谨慎，心胸宽广容纳所有好的坏的、先苦后甜
 * day39bookshop
 * 2021/4/29 13:54
 */
@WebServlet(value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        String vcode = req.getParameter("vcode");
        if(StringUtils.isEmptry(username)){
            resp.getWriter().write("用户名不能为空");
            return;
        }
        if(StringUtils.isEmptry(pwd)){
            resp.getWriter().write("密码不能为空");
            return;
        }
        if(StringUtils.isEmptry(vcode)){
            resp.getWriter().write("验证码不能为空");
            return;
        }
        //校验验证码
        String code =(String)req.getSession().getAttribute("code");
        if(!vcode.equalsIgnoreCase(code)){
            resp.getWriter().write("验证码输入有误");
            return;
        }

        UserService userService = new UserServiceImpl();
        try {
            User user=userService.login(username,pwd);
            //登录成功后需要把user存在session中
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            //重定向
//            resp.sendRedirect("index.jsp");
            resp.sendRedirect("booklists");
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendRedirect("message.html");
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
